﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.Contacts;
using SocialNetworksServices.Google.Contacts;
using GDesktop.Service;
using GDesktop.Service.DTO;
using System.Drawing;
using System.IO;

namespace GDesktop.Service
{
    public class ContatosService
    {

        public ContatosService(string pAplicationName, string pLogin, string pPassword)
        {
            ContactsService = new GContactsService(pAplicationName, pLogin, pPassword);
        }

        public GContactsService ContactsService { get; set; }

        public List<Group> GetAllGroups()
        {
            return ContactsService.GetAllContactGroups();
        }

        public List<ContactsDTO> GetContactsByGroup(string pGroupID)
        {
            List<Contact> listaContatos = ContactsService.GetAllContactsByGroup(pGroupID);

            List<ContactsDTO> listaRetorno = new List<ContactsDTO>();

            foreach (var item in listaContatos)
            {
                listaRetorno.Add(new ContactsDTO(item));
            }
            return listaRetorno;
        }

        public Image GetImageFromContact(string pContactID)
        {
            Stream str = ContactsService.GetPhotoStreamByContact(pContactID);

            byte[] b = new byte[1024];
            List<byte> buffer = new List<byte>();
            int leido = 0;
            do
            {
                leido = str.Read(b, 0, b.Length);
                if (leido == 1024)
                    buffer.AddRange(b);
                else
                {
                    byte[] b2 = new byte[leido];
                    Array.Copy(b, b2, leido);
                    buffer.AddRange(b2);
                }
            } while (leido == 1024);
            b = buffer.ToArray();

            MemoryStream imageStream = new MemoryStream(b, 0, b.Length);

            return Image.FromStream(imageStream);
        }

        public ContactsDTO GetContactDTOByID(string pContactID)
        {

            Contact contato = ContactsService.GetAllContactByID(pContactID);

            ContactsDTO retorno = new ContactsDTO(contato);

            retorno.Photo = this.GetImageFromContact(pContactID);

            return retorno;
        }
    }
}
